package com.kfm.mvn.filter;

import com.kfm.mvn.util.Constant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

@WebFilter("/*")
public class LoginFilter implements Filter {

    private static List<String> excludePathList = List.of("/", "/index.html", "/hello.html", "/captcha", "/login", "/static/");
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        // 判断资源类型
        String uri = httpServletRequest.getRequestURI();

        String path = uri.replace(httpServletRequest.getContextPath(), "");

        // 静态资源放行, 是否是 static 请求
        if (path.startsWith("/static/")) {
            chain.doFilter(request, response);
            return;
        }

        // 登录页面请求放行
        if (excludePathList.contains(path)){
            chain.doFilter(request, response);
            return;
        }

        // 判断是否登录
        HttpSession session = httpServletRequest.getSession();

        Object attribute = session.getAttribute(Constant.LOGIN_USER);
        if (attribute != null){
            // 登录过
            chain.doFilter(request, response);
            return;
        }

        ((HttpServletResponse)response).sendRedirect(httpServletRequest.getContextPath() + "/");

    }
}
